import config from '@/config'
import { WidgetOption, WidgetStyle, WidgetType, FillRadioType } from '@/types'
import { CheckOption } from '@/models'
import WidgetCheckGroup from './WidgetCheckGroup.vue'
import CheckGroupSetting from './CheckGroupSetting.vue'
import CheckGroupFill from './CheckGroupFill.vue'

/** 复选框 */
export default {
  key: 'checkbox-group',
  name: '复选框',
  type: WidgetType.CHECKBOX_GROUP,
  style: WidgetStyle.FILL,
  icon: 'fa-icon-widget-checkbox',
  width: 32,
  height: 32,
  component: WidgetCheckGroup,
  settingComponent: CheckGroupSetting,
  fillingComponent: CheckGroupFill,

  /** 初始控件数据 */
  init(widget, data) {
    const { space, height } = config.checkOption
    const { type, y, ox, value } = widget

    const options =
      data.checkOptions ||
      // 初始选项列表，复选框只生成一个
      Array.from(
        new Array(type === WidgetType.CHECKBOX_GROUP ? 1 : 2),
        (item, index) =>
          ({
            label: `选项${index + 1}`
          } as Partial<CheckOption>)
      )

    let values: boolean[] = []

    try {
      if (value && typeof value === 'string') {
        values = JSON.parse(value)
      }
    } catch (e) {}

    if (!Array.isArray(values)) values = []

    widget.checkOptions =
      options.map((item, index) => {
        let option = { ...item }
        // 子项未指定坐标则初始化
        if (item.x === undefined && item.ox === undefined) {
          Object.assign(option, {
            ox,
            y: y + space + (height + space * 2 - 1) * index
          })
        }

        // 初始选项值
        option.value = values[index] ?? option.value

        return new CheckOption(option)
      }) || []
  },

  settingValidate(widget) {
    if (widget.checkOptions.some(option => !option.label)) {
      return '请设置选项值'
    }
  },

  usingValidate(widget) {
    if (widget.required && !widget.hasFillValue) return `请选择${widget.displayName}`
  },

  hasFillValue(widget) {
    return widget.checkOptions.some(item => item.value)
  },

  rawWidgetCreator(widgetData, data) {
    const { childWidgetList: options } = data

    return Object.assign(widgetData, {
      checkOptions: (options || []).map(
        ({ widgetName: label, widgetValue: value, x: ox, y: oy }, index) =>
          ({
            label,
            ox,
            oy,
            value
          } as Partial<CheckOption>)
      )
    })
  },

  rawFieldGetter(widget, data) {
    const { type, p, required: isRequired, checkOptions } = widget

    const radioType = type === WidgetType.RADIO_GROUP ? FillRadioType.RADIO : undefined

    return Object.assign(data, {
      childWidgetList: checkOptions.map(item => ({
        type,
        p,
        w: Math.floor(item.w),
        h: Math.floor(item.h),
        x: Math.floor(item.ox),
        y: Math.floor(item.oy),
        widgetName: item.label,
        widgetValue: item.value,
        radioType,
        showBorder: false,
        isRequired
      }))
    })
  }
} as WidgetOption
